package cc.linker.steplink.crm.merchanth5.controller;


import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.pojo.OrderGoods;
import cc.linker.steplink.crm.merchanth5.service.EnrollActiveService;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.merchanth5.util.ParamSignUtils;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 卖爆啦H5
 */
@Slf4j
@RestController
@RequestMapping("/mallboom")
public class MallBoomController {

    @Autowired
    private MallBoomService mallBoomService;

    @Autowired
    private MallService mallService;

    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private MaiBaoLaService maiBaoLaService;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private HttpService httpService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PurchaseProcessService purchaseProcessService;

    @Autowired
    private PurchaseProcessDao purchaseProcessDao;

    @Autowired
    private EnrollActiveService enrollActiveService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RequestFilter requestFilter;

    @Value("${system.scrm.acsScrmWebUrl}")
    private String scrmH5Url;
    @Value("${casclient.clientHost}")
    private String clientHost;
    @Value("${wcpay.payurl}")
    private String payurl;
    @Value("${wcpay.smsurl}")
    private String smsurl;
    @Value("${system.scrm.getwxlist}")
    private String doAddbAccountUrl;
    @Value("${system.scrm.sync.contentUrl}")
    private String synccontentUrl;

    /**
     * 获取加盟费
     *
     * @param request
     * @return
     */
    @PostMapping("/getjoininfo")
    public Object getJoinInfo(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        Integer amount = mallBoomService.getJoinMoney(orgId);
        Integer seniorAmount = mallBoomService.getJoinMoneyPromoter(orgId);
        params.put("amount", amount);
        params.put("seniorAmount", seniorAmount);
        return params;
    }

    ;


    @PostMapping("/getjoinstatus")
    public Object getJoinStatus(HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        String customerId = wxUser.getCustomerId();
        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("orgId", orgId);
        salerParam.put("customerId", customerId);
        salerParam.put("orderType", "saler");
        HashMap<String, Object> joinStatus = mallBoomService.getJoinStatus(salerParam);
        String authenticateState = "0";
        String goodNum = "0";
        String hasBussnessImg = "0";
        String promoter = "0";
        String verifyStatus = "0";
        if (null != joinStatus) {
            if (!joinStatus.get("phone").equals("")) {
                authenticateState = "1";
            }
            goodNum = joinStatus.get("goodNum").toString();
            hasBussnessImg = joinStatus.get("authenticateState").toString().equals("0") ? "0" : "1";
            verifyStatus = joinStatus.get("authenticateState").toString().equals("1") ? "1" : "0";
        }
        HashMap<String, Object> salerOrder = mallBoomService.getSalerOrder(salerParam);
        String payStatus = "0";
        if (null != salerOrder) {
            payStatus = salerOrder.get("payStatus").toString();
        }
        //判断该用户是否是高级推广员
        Integer ifPromoter = mallBoomService.getPromoterCount(salerParam);
        if (ifPromoter > 0) {
            promoter = "1";
        }

        Map<String, String> salerData = new HashMap<>();
        salerData.put("authenticateState", authenticateState);
        salerData.put("goodNum", goodNum);
        salerData.put("payStatus", payStatus);
        salerData.put("hasBussnessImg", hasBussnessImg);
        salerData.put("verifyStatus", verifyStatus);
        salerData.put("promoter", promoter);
        return salerData;
    }


    /**
     * 创建加盟订单
     *
     * @param params
     * @param request
     * @return
     * @throws GlobalException
     */
    @PostMapping("/getsign")
    public Object getSign(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        String openId = wxUser.getOpenid();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
        SortedMap<String, Object> finalpackage = new TreeMap<>();

        Integer sysAmount = mallBoomService.getJoinMoney(orgId);
        if (null == params.get("amount")) {
            throw GlobalException.build("参数错误");
        }
        if (sysAmount != Integer.parseInt(params.get("amount").toString())) {
            throw GlobalException.build("金额不一致，请重试");
        }
        String pid = "";
        if (!StringUtils.isEmpty(params.get("pid"))) {
            pid = params.get("pid").toString();
        }
        String tid = "";
        if (!StringUtils.isEmpty(params.get("tid"))) {
            tid = params.get("tid").toString();
        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "saler");
        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);

        Map<String, String> orderParam = new HashMap<>();
        Long currentTime = new Date().getTime();
        String notifyUrl = systemProperties.getScrmUrl() + "mallboom/ordernotify";


        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {//订单未支付,取订单信息去支付
                Map<String, String> tmpParam = new HashMap<>();
                tmpParam.put("amount", sysAmount.toString());
                tmpParam.put("orderSn", orderSn);
                tmpParam.put("pid", pid);
                tmpParam.put("tid", tid);
                tmpParam.put("customerId", customerId);
                tmpParam.put("orgId", orgId);
                tmpParam.put("orderType", "saler");
                mallBoomService.editSalerOrder(tmpParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入，请勿重复加入");
            }
        } else {//没有订单，创建订单去支付

            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orderSn", orderSn);
            tmpParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            tmpParam.put("amount", sysAmount.toString());
            tmpParam.put("pid", pid);
            tmpParam.put("tid", tid);
            tmpParam.put("orgId", orgId);
            tmpParam.put("customerId", customerId);
            tmpParam.put("payStatus", "0");
            tmpParam.put("orderType", "saler");
            mallBoomService.addSalerOrder(tmpParam);
        }

        orderParam.put("body", "加入联盟商家");
        orderParam.put("notifyUrl", notifyUrl);
        orderParam.put("openid", openId);
        orderParam.put("outTradeNo", orderSn);
        orderParam.put("timestamp", currentTime.toString());
        orderParam.put("totalFee", sysAmount.toString());
        orderParam.put("tradeType", "JSAPI");
        orderParam.put("wcpayType", "STEPLINK_" + orgId);

        Map<String, String> appSign = ParamSignUtils.sign(orderParam);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("appSign", appSign.get("appSign")));
        nvps.add(new BasicNameValuePair("notifyUrl", orderParam.get("notifyUrl")));
        nvps.add(new BasicNameValuePair("body", orderParam.get("body")));
        nvps.add(new BasicNameValuePair("outTradeNo", orderParam.get("outTradeNo")));
        nvps.add(new BasicNameValuePair("openid", orderParam.get("openid")));
        nvps.add(new BasicNameValuePair("timestamp", orderParam.get("timestamp")));
        nvps.add(new BasicNameValuePair("totalFee", orderParam.get("totalFee")));
        nvps.add(new BasicNameValuePair("tradeType", orderParam.get("tradeType")));
        nvps.add(new BasicNameValuePair("wcpayType", orderParam.get("wcpayType")));
        String result = ParamSignUtils.callService(payurl + "/pay/wcpay", nvps, 0, 0);
        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("微信签名失败");
        } else {
            Map retInfo = (Map) ret.get("object");
            finalpackage.put("appId", retInfo.get("appId"));
            finalpackage.put("timeStamp", retInfo.get("timeStamp"));
            finalpackage.put("nonceStr", retInfo.get("nonceStr"));
            finalpackage.put("package", "prepay_id=" + retInfo.get("prepayId"));
            finalpackage.put("signType", retInfo.get("signType"));
            finalpackage.put("paySign", retInfo.get("paySign"));
            finalpackage.put("orderSn", orderSn);
        }
        return finalpackage;
    }

    /**
     * 创建高级推广员订单
     *
     * @param params
     * @param request
     * @return
     * @throws GlobalException
     */
    @PostMapping("/getsignpromoter")
    public Object getSignPromoter(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        String openId = wxUser.getOpenid();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
        SortedMap<String, Object> finalpackage = new TreeMap<>();

        HashMap<Object, Object> salerNowMap = new HashMap<>();
        salerNowMap.put("orgId", orgId);
        salerNowMap.put("customerId", customerId);
        Integer salerNowCount = mallBoomService.getSalerCount(salerNowMap);
        if (salerNowCount > 0) {
            throw GlobalException.build("你已是联盟商家，无需开通");
        }

        Integer sysAmount = mallBoomService.getJoinMoneyPromoter(orgId);
        if (null == params.get("amount")) {
            throw GlobalException.build("参数错误");
        }
        if (sysAmount != Integer.parseInt(params.get("amount").toString())) {
            throw GlobalException.build("金额不一致，请重试");
        }
        String pid = "";
        if (!StringUtils.isEmpty(params.get("pid"))) {
            pid = params.get("pid").toString();
            //判断分享人是否是麦或高级推广员
            HashMap<Object, Object> salerMap = new HashMap<>();
            salerMap.put("orgId", orgId);
            salerMap.put("customerId", pid);
            Integer salerCount = mallBoomService.getSalerCount(salerMap);
            Integer promoterCount = mallBoomService.getPromoterCount(salerMap);
            if (salerCount < 1 && promoterCount < 1) {
                throw GlobalException.build("分享人异常");
            }
        }
        String tid = "";
        if (!StringUtils.isEmpty(params.get("tid"))) {
            tid = params.get("tid").toString();
        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "promoter");
        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);

        Map<String, String> orderParam = new HashMap<>();
        Long currentTime = new Date().getTime();
        String notifyUrl = systemProperties.getScrmUrl() + "mallboom/ordernotify";

        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {//订单未支付,取订单信息去支付
                Map<String, String> tmpParam = new HashMap<>();
                tmpParam.put("amount", sysAmount.toString());
                tmpParam.put("orderSn", orderSn);
                tmpParam.put("pid", pid);
                tmpParam.put("tid", tid);
                tmpParam.put("customerId", customerId);
                tmpParam.put("orgId", orgId);
                tmpParam.put("orderType", "promoter");
                mallBoomService.editSalerOrder(tmpParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入，请勿重复加入");
            }
        } else {//没有订单，创建订单去支付

            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orderSn", orderSn);
            tmpParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            tmpParam.put("amount", sysAmount.toString());
            tmpParam.put("pid", pid);
            tmpParam.put("tid", tid);
            tmpParam.put("orgId", orgId);
            tmpParam.put("customerId", customerId);
            tmpParam.put("payStatus", "0");
            tmpParam.put("orderType", "promoter");
            mallBoomService.addSalerOrder(tmpParam);
        }

        orderParam.put("body", "加盟代理");
        orderParam.put("notifyUrl", notifyUrl);
        orderParam.put("openid", openId);
        orderParam.put("outTradeNo", orderSn);
        orderParam.put("timestamp", currentTime.toString());
        orderParam.put("totalFee", sysAmount.toString());
        orderParam.put("tradeType", "JSAPI");
        orderParam.put("wcpayType", "STEPLINK_" + orgId);

        Map<String, String> appSign = ParamSignUtils.sign(orderParam);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("appSign", appSign.get("appSign")));
        nvps.add(new BasicNameValuePair("notifyUrl", orderParam.get("notifyUrl")));
        nvps.add(new BasicNameValuePair("body", orderParam.get("body")));
        nvps.add(new BasicNameValuePair("outTradeNo", orderParam.get("outTradeNo")));
        nvps.add(new BasicNameValuePair("openid", orderParam.get("openid")));
        nvps.add(new BasicNameValuePair("timestamp", orderParam.get("timestamp")));
        nvps.add(new BasicNameValuePair("totalFee", orderParam.get("totalFee")));
        nvps.add(new BasicNameValuePair("tradeType", orderParam.get("tradeType")));
        nvps.add(new BasicNameValuePair("wcpayType", orderParam.get("wcpayType")));
        String result = ParamSignUtils.callService(payurl + "/pay/wcpay", nvps, 0, 0);
        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("微信签名失败");
        } else {
            Map retInfo = (Map) ret.get("object");
            finalpackage.put("appId", retInfo.get("appId"));
            finalpackage.put("timeStamp", retInfo.get("timeStamp"));
            finalpackage.put("nonceStr", retInfo.get("nonceStr"));
            finalpackage.put("package", "prepay_id=" + retInfo.get("prepayId"));
            finalpackage.put("signType", retInfo.get("signType"));
            finalpackage.put("paySign", retInfo.get("paySign"));
            finalpackage.put("orderSn", orderSn);
        }
        return finalpackage;
    }

    /**
     * 直接加盟（金额0）
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/joinboom")
    public Object joinBoom(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        Integer amount = mallBoomService.getJoinMoney(orgId);
        if (amount > 0) {
            throw GlobalException.build("非法操作");
        }

        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getSalerCount(tmpParam);
        if (salerCount > 0) {
            throw GlobalException.build("你已加入，请勿重复加入");
        }

        String pid = "";
        if (null != params.get("pid") && !"".equals(params.get("pid"))) {
            pid = params.get("pid");
        }

//        String tid = "";
//        if (null != params.get("tid") && !"".equals(params.get("tid"))) {
//            tid = params.get("tid");
//        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "saler");

        Map<String, String> ordParam = new HashMap<>();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
        ordParam.put("orderSn", orderSn);
        ordParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        ordParam.put("amount", "0");
        ordParam.put("pid", pid);
//        ordParam.put("tid", tid);
        ordParam.put("orgId", orgId);
        ordParam.put("customerId", customerId);
        ordParam.put("payStatus", "1");
        ordParam.put("orderType", "saler");

        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);
        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {
                ordParam.put("orderSn", salerOrderInfo.get("orderSn").toString());
                mallBoomService.editSalerOrder(ordParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入，请勿重复加入");
            }
        } else {
            mallBoomService.addSalerOrder(ordParam);
        }
        return this.addSaler(pid, customerId, orgId, 0);
    }

    /**
     * 直接加盟高级推广员（金额0）
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/joinpromoter")
    public Object joinPromoter(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getPromoterCount(tmpParam);
        if (salerCount > 0) {
            throw GlobalException.build("你已加入，请勿重复加入");
        }
        Integer isNowSaler = mallBoomService.getSalerCount(tmpParam);
        if (isNowSaler > 0) {
            throw GlobalException.build("你已是联盟商家，无需开通");
        }

        String isSaler = "";
        String pid = "";
        if (null == params.get("pid") || "".equals(params.get("pid"))) {
            throw GlobalException.build("参数错误，非法操作");
        }
        if (null != params.get("pid") && !"".equals(params.get("pid"))) {
            pid = params.get("pid");
            //判断分享人是否是麦或高级推广员
            HashMap<Object, Object> salerMap = new HashMap<>();
            salerMap.put("orgId", orgId);
            salerMap.put("customerId", pid);
            Integer checkSalerCount = mallBoomService.getSalerCount(salerMap);
            if (checkSalerCount > 0) {
                isSaler = "1";
            }
            Integer promoterCount = mallBoomService.getPromoterCount(salerMap);
            if (checkSalerCount < 1 && promoterCount < 1) {
                throw GlobalException.build("分享人异常");
            }
        }

        Integer amount = mallBoomService.getJoinMoneyPromoter(orgId);
        if (amount > 0 && "".equals(isSaler)) {
            throw GlobalException.build("非法操作");
        }
//        String tid = "";
//        if (null != params.get("tid") && !"".equals(params.get("tid"))) {
//            tid = params.get("tid");
//        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "promoter");

        Map<String, String> ordParam = new HashMap<>();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
        ordParam.put("orderSn", orderSn);
        ordParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        ordParam.put("amount", "0");
        ordParam.put("pid", pid);
//        ordParam.put("tid", tid);
        ordParam.put("orgId", orgId);
        ordParam.put("customerId", customerId);
        ordParam.put("payStatus", "1");
        ordParam.put("orderType", "promoter");

        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);
        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {
                ordParam.put("orderSn", salerOrderInfo.get("orderSn").toString());
                mallBoomService.editSalerOrder(ordParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入，请勿重复加入");
            }
        } else {
            mallBoomService.addSalerOrder(ordParam);
        }
        return mallBoomService.savePromoter(customerId);
    }

    /**
     * 加盟订单回调
     *
     * @param params
     * @return
     */
    @PostMapping("/ordernotify")
    public void orderNotify(@RequestBody Map<String, Object> params) {
        String transactionId = (String) params.get("transactionId");//商户订单号
        String outTradeNo = (String) params.get("outTradeNo");//商户订单号
        String totalFeeStr = (String) params.get("totalFee");//订单金额
        Integer totalFee = Integer.valueOf(totalFeeStr);
        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrderBySn(outTradeNo);
        Long amount = (Long) salerOrderInfo.get("amount");
        if (totalFee == amount.intValue()) {
            Map<String, Object> orderParam = new HashMap<>();
            orderParam.put("tradeSn", transactionId);
            orderParam.put("paymentTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            orderParam.put("orderSn", outTradeNo);
            mallBoomService.doneSalerOrder(orderParam);
            // orderType
            String orderType = salerOrderInfo.get("orderType").toString();// 订单类型：saler开通麦爆啦，promoter开通高推

            String pid = salerOrderInfo.getOrDefault("pid", "").toString();// 邀请人id
//            String tid = salerOrderInfo.getOrDefault("tid", "").toString();// 邀请人id
            String customerId = salerOrderInfo.get("customerId").toString();
            String orgId = salerOrderInfo.get("orgId").toString();
            Map<String, Integer> reverseProfitModel = mallBoomService.getReverseProfitModel(orgId);// 返润模式busi_mallboom_org
            if (reverseProfitModel == null) {
                // 机构未设置返润模式
                LOGGER.error("机构未设置返润不应产生支付回调！流水号[{}]订单号[{}]订单金额[{}]", transactionId, outTradeNo, totalFeeStr);
                LOGGER.error("Payment callbacks should not be generated if the institution does not set up a return profit!" +
                        "transactionId[{}]outTradeNo[{}]totalFeeStr[{}]", transactionId, outTradeNo, totalFeeStr);
                return;
            }
            Integer rebate = reverseProfitModel.get("rebate");// 入盟费分成比例(开通麦服务费)
            Integer rebateRf = reverseProfitModel.get("recommend");// 入盟费分成比例(开通麦推荐费)
            Integer seniorRebate = reverseProfitModel.get("seniorRebate");// 入盟费分成比例(开通高推服务费)
            rebate = rebate == null ? 0 : rebate;
            rebateRf = rebateRf == null ? 0 : rebateRf;
            seniorRebate = seniorRebate == null ? 0 : seniorRebate;
            double v = totalFee.doubleValue() * rebate.doubleValue() / 100;
            int i = new BigDecimal(v).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();// 麦服务费
            double v1 = totalFee.doubleValue() * rebateRf.doubleValue() / 100;
            int j = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();// 麦推荐费
            double v2 = totalFee.doubleValue() * seniorRebate.doubleValue() / 100;
            int k = new BigDecimal(v2).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();// 高推推荐费
            String salerId = mallBoomService.findPid(customerId);// 上级id
            boolean ifRf = !StringUtils.isEmpty(salerId) && j != 0 && !salerId.equals(customerId);// 开麦是否产生推荐费(true:产生,false:不产生)
            boolean ifFw = !StringUtils.isEmpty(pid) && i != 0 && !pid.equals(customerId);// 开麦是否产生服务费(true:产生,false:不产生)
            boolean ifGfw = !StringUtils.isEmpty(pid) && k != 0;// 开高推是否产生服务费(true:产生,false:不产生)
            if ("saler".equals(orderType)) {
                // 开通麦爆啦
                if (ifFw && ifRf) {// 服务费+推荐费
                    this.addSaler(pid, customerId, orgId, amount.intValue());
                    // 平台
                    this.addAccountTrade(customerId, "4", orgId, "", "0",
                            outTradeNo, transactionId, totalFee - i - j, customerId);
                    // 服务费
                    this.addAccountTrade(customerId, "3", orgId, pid, "1",
                            outTradeNo, transactionId, i, customerId);
                    // 推荐费
                    this.addAccountTrade(customerId, "6", orgId, salerId, "2",
                            outTradeNo, transactionId, j, customerId);
                } else if (ifFw) {// 服务费
                    this.addSaler(pid, customerId, orgId, amount.intValue());
                    // 平台
                    this.addAccountTrade(customerId, "4", orgId, "", "0",
                            outTradeNo, transactionId, totalFee - i, customerId);
                    // 服务费
                    this.addAccountTrade(customerId, "3", orgId, pid, "1",
                            outTradeNo, transactionId, i, customerId);
                } else if (ifRf) {// 推荐费
                    this.addSaler(null, customerId, orgId, amount.intValue());
                    // 平台
                    this.addAccountTrade(customerId, "4", orgId, "", "0",
                            outTradeNo, transactionId, totalFee - j, customerId);
                    // 推荐费
                    this.addAccountTrade(customerId, "6", orgId, salerId, "2",
                            outTradeNo, transactionId, j, customerId);
                } else {// 仅平台
                    this.addSaler(null, customerId, orgId, amount.intValue());
                    // 平台
                    this.addAccountTrade(customerId, "4", orgId, "", "0",
                            outTradeNo, transactionId, totalFee, customerId);
                }
            } else if ("promoter".equals(orderType)) {
                // 开通高级推广员
                mallBoomService.savePromoter(customerId);
                if (ifGfw) {// 有服务费
                    // 平台
                    this.addAccountTrade(customerId, "7", orgId, "", "0",
                            outTradeNo, transactionId, totalFee - k, customerId);
                    // 服务费
                    this.addAccountTrade(customerId, "8", orgId, pid, "1",
                            outTradeNo, transactionId, k, customerId);
                } else {// 没服务费
                    // 平台
                    this.addAccountTrade(customerId, "7", orgId, "", "0",
                            outTradeNo, transactionId, totalFee, customerId);
                }
            } else {
                LOGGER.error("订单类型不正确！加盟订单回调执行失败！流水号[{}]订单号[{}]订单金额[{}]", transactionId, outTradeNo, totalFeeStr);
                LOGGER.error("The order type is incorrect! Franchise order callback failed to execute!" +
                        "transactionId[{}]outTradeNo[{}]totalFeeStr[{}]", transactionId, outTradeNo, totalFeeStr);
            }
//            if (StringUtils.isEmpty(pid) && StringUtils.isEmpty(tid)) {//没有分享人.没有服务费
//                this.addSaler(null, customerId, orgId, amount.intValue());
//                if (ifRf) {
//                    // 有推荐费，无服务费，平台获得
//                    this.addAccountTrade(customerId, "4", orgId, "", "0",
//                            outTradeNo, transactionId, totalFee - j, customerId);
//                    // 推荐费，上级获得
//                    this.addAccountTrade(customerId, "6", orgId, salerId, "2",
//                            outTradeNo, transactionId, j, customerId);
//                } else {
//                    // 无推荐费、无服务费，平台获得
//                    this.addAccountTrade(customerId, "4", orgId, "", "0",
//                            outTradeNo, transactionId, totalFee, customerId);
//                }
//            } else {//有分享人.有服务费
//                if (recommendState) {
//                    // 推荐费模式(2级返润)
//                    this.addSaler(pid, customerId, orgId, amount.intValue());
//                    // pid空,tid不空(有tid必有pid,所以不用考虑tid空pid不空的情况)
//                    // pid空,且只能给麦返,结果为不返服务费,根据ifRf判断是否返推荐费
//                    if (StringUtils.isEmpty(pid) && !rebateState) {
//                        // 平台获得
//                        this.addAccountTrade(customerId, "4", orgId, "", "0",
//                                outTradeNo, transactionId, ifRf ? totalFee - j : totalFee, customerId);
//                    } else {
//                        // pid空,给tid返
//                        // 都不空,返服务费
//                        // 平台获得
//                        this.addAccountTrade(customerId, "4", orgId, "", "0",
//                                outTradeNo, transactionId, ifRf ? totalFee - i - j : totalFee - i, customerId);
//                        // 服务费
//                        // 分享人获得
//                        if (rebate != 0) {
//                            this.addAccountTrade(customerId, "3", orgId, rebateState ? tid : pid, "1",
//                                    outTradeNo, transactionId, i, customerId);
//                        }
//                    }
//                    if (ifRf) {
//                        // 2级返,推荐费
//                        // 上级获得
//                        this.addAccountTrade(customerId, "6", orgId, salerId, "2",
//                                outTradeNo, transactionId, j, customerId);
//                    }
//                } else {
//                    // 非推荐费模式(1级返润)
//                    this.addSaler(pid, customerId, orgId, amount.intValue());
//                    // 平台获得
//                    this.addAccountTrade(customerId, "4", orgId, "", "0",
//                            outTradeNo, transactionId, totalFee - i, customerId);
//                    // 服务费为0,不产生记录
//                    if (rebate != 0) {
//                        // 分享人获得
//                        this.addAccountTrade(customerId, "3", orgId, rebateState ? tid : pid, "1",
//                                outTradeNo, transactionId, i, customerId);
//                    }
//                }
//            }
        } else {
            //订单金额和支付金额不相同啊，怎么办.订单回滚吗
            LOGGER.error("订单金额和支付金额不相同," +
                            "Order amount and payment amount are different,transactionId[{}]outTradeNo[{}]totalFeeStr[{}]",
                    transactionId, outTradeNo, totalFeeStr);
        }
    }

    // 递归查询某cid的父级id(mode=true只查麦)
    private String findPid(String cid) {
        return mallBoomService.findPid(cid);
//        if (!mode) {
//            return pid;
//        }
//        if (pid == null) {
//            return null;
//        }
//        boolean isS = mallBoomService.isSalerByCid(pid);
//        if (isS) {
//            return pid;
//        } else {
//            return findPid(pid, true);
//        }
    }

    /**
     * 保存用户关系
     *
     * @param pid
     * @param customerId
     * @param orgId
     * @param payMoney
     * @return
     */
    private Boolean addSaler(String pid, String customerId, String orgId, Integer payMoney) {
        Map<String, Object> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("pid", pid);
        salerParam.put("joinTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        salerParam.put("payMoney", payMoney);
        salerParam.put("orgId", orgId);
        salerParam.put("phone", "");
        int count = mallBoomService.getSalerCount(salerParam);
        if (count > 0) {
            return true;
        } else {
            return mallBoomService.addSaler(salerParam);
        }
    }

    /**
     * 保存账单明细
     *
     * @param payAccountId  付款人ID
     * @param tradeSubType  活动营销子类型：1.订单收益2.商品返利3.邀请返利4.平台收入
     * @param orgId
     * @param salerId       归属人/分享人
     * @param belongState   0归属人1分享人
     * @param payInfo       商户单号
     * @param tradeOrderNum 交易流水号
     * @param tradeSum      交易金额
     * @param payUser       付款人
     * @return
     */
    private Boolean addAccountTrade(String payAccountId, String tradeSubType, String orgId, String salerId, String belongState,
                                    String payInfo, String tradeOrderNum, Integer tradeSum, String payUser) {
        Map<String, Object> tradeParam = new HashMap<>();
        tradeParam.put("payAccountId", payAccountId);
        tradeParam.put("tradeType", 1);
        tradeParam.put("tradeSubType", tradeSubType);
        tradeParam.put("orgId", orgId);
        tradeParam.put("salerId", salerId);
        tradeParam.put("belongState", belongState);
        tradeParam.put("chargeType", 2);
        tradeParam.put("payInfo", payInfo);
        tradeParam.put("tradeOrderNum", tradeOrderNum);
        tradeParam.put("tradeSum", tradeSum);
        tradeParam.put("sumRmb", tradeSum);
        tradeParam.put("payUser", payUser);
        tradeParam.put("settlementState", 1);
        tradeParam.put("tradeTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        tradeParam.put("reciveUser", salerId);
        return mallBoomService.addAccountTrade(tradeParam);
    }

    /**
     * 绑定手机号
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/savephone")
    public Boolean savephone(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException, IOException, URISyntaxException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        params.put("orgId", orgId);
        params.put("customerId", customerId);
//        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//        nvps.add(new BasicNameValuePair("businessType", "1020"));
//        nvps.add(new BasicNameValuePair("plantName", "STEPLINK"));
//        nvps.add(new BasicNameValuePair("mobilNumber", params.get("phone")));
//        nvps.add(new BasicNameValuePair("randomCode", params.get("code")));
//        String result = ParamSignUtils.callService(smsurl + "/sms/checkVerificationCode", nvps, 0, 0);

        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", "1020");
        nvps.put("mobilNumber", params.get("phone"));
        nvps.put("randomCode", params.get("code"));
        String result = smsService.checkVerification(orgId, nvps);

        Map ret = (Map) JSON.parse(result);
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("验证码失效");
        }

        //生成小b用于登录cas的账号
        String casUserName = "mbl" + params.get("phone") + orgId;
        String casPassword = getRandom(6);
        Map<String, Object> pushData = new HashMap<>();
        pushData.put("orgcode", orgId);
        pushData.put("account", casUserName);
        pushData.put("username", wxUser.getNickname());
        pushData.put("pwd", DigestUtils.md5DigestAsHex(casPassword.getBytes()));
        String postres = httpService.doGet(doAddbAccountUrl + "?action=doAddbAccount", pushData);
        if (null == postres) {
            throw GlobalException.build("验证失败，请重试");
        }
        Map res = (Map) JSON.parse(postres);
        if ((Integer) res.get("RetCode") != 0) {
            switch ((Integer) res.get("RetCode")) {
                case 3:
                    throw GlobalException.build("你已是麦爆啦店主，请勿重复开通");
                case 5:
                    throw GlobalException.build("用户达到上限，请联系管理员");
            }
            throw GlobalException.build("系统繁忙，请稍后再试");
        }
        params.put("casUserId", res.get("UserID").toString());
        params.put("casUserName", casUserName);
        params.put("casPassword", casPassword);
        //TODO 1.9.2
        Map<String, Object> phoneData = new HashMap<>();
        phoneData.put("bindPhone", params.get("phone"));
        phoneData.put("customerId", customerId);
        mallBoomService.updateBindPhoneByCid(phoneData);
        //mallBoomService.saveCustomerPhone(customerId, params.get("phone"));
        return mallBoomService.savephone(params);
    }

    /**
     * 生成指定位数随机数
     *
     * @param length
     * @return
     */
    protected static String getRandom(int length) {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val.append(random.nextInt(10));
        }
        return val.toString();
    }


    /**
     * 绑定手机号
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/sendVerificationCode")
    public Object sendVerificationCode(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        Integer payMode = wxUser.getPayMode();

        // 判断app用户
        Map<String,Object> appMemberInfo = maiBaoLaService.getAppCustomerByCid(customerId);
        if(!StringUtils.isEmpty(appMemberInfo) && (payMode==2 || payMode==3)){
            // 判断新老手机号
            int oldPhone= maiBaoLaService.checkOldPhone(params.get("phone"),orgId)>0?1:0;
            // 判断是否已经绑定过手机号
            String bindPhone = maiBaoLaService.getBindPhoneByCustomerId(customerId);
            if(StringUtils.isEmpty(bindPhone) && oldPhone==0){
                try {
                    // 新手机调用通联开户接口
                    Map<String, Object> map = new HashMap<>();
                    map.put("customerId", customerId);
                    map.put("customerPhone",params.get("phone"));
                    map.put("orgId", orgId);
                    map.put("acctType", "XCX");
                    LOGGER.info("App用户发送通联开户短信验证码param: "+com.alibaba.fastjson.JSON.toJSONString(map));
                    maiBaoLaService.checkCustomerAccount(map,payMode);
                    return true;
                }catch (Exception e) {
                    LOGGER.error("新手机调用通联开户接口", e);
                    throw GlobalException.build("系统错误");
                }
            }
        }
        String token = wxUser.getToken();
        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", "1020");
        nvps.put("mobilNumber", params.get("phone"));
        nvps.put("params", "");
        nvps.put("token", "");
        LOGGER.info("用户发送短信验证码param: " + com.alibaba.fastjson.JSON.toJSONString(nvps));
        String result = smsService.sendVerification(token, nvps);
        LOGGER.info("用户发送短信验证码result: " + result);
        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("验证码发送失败");
        }
        return true;
    }

    /**
     * 获取当前用户推荐的麦爆成员
     *
     * @param request
     * @return
     */
    @PostMapping("/getsonboomlist")
    public Object getSonBoomList(HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        List<Map<String, String>> sonList = mallBoomService.getSonBoomList(customerId);
        Map<String, Object> data = new HashMap<>();
        data.put("count", sonList.size());
        data.put("sonList", sonList);
        return data;
    }

    /**
     * 舍弃 后台上传
     */
//    @PostMapping("/savebusinessimg")
//    public void saveBusinessImg(@RequestBody Map<String, String> params,HttpServletRequest request) throws GlobalException {
//        WxUser wxUser =  requestFilter.getWxUser(request);
//        String customerId = wxUser.getCustomerId();
//        if(null == params.get("businessImg") || "".equals(params.get("businessImg"))){
//            throw GlobalException.build("请上传营业执照");
//        }
//        params.put("customerId",customerId);
//        mallBoomService.saveBusinessImg(params);
//    }

    /**
     * 获取卖爆订单
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/getSalerOrderList")
    public Object getOrderList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        params.put("salerId", customerId);
        String orgId = wxUser.getOrgId();
        params.put("orgId", orgId);
        return mallService.getSalerOrderList(params);
    }

    @GetMapping("/getmyboom")
    public Object getMyBoom(HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        return mallBoomService.getMyBoom(customerId);
    }

    /**
     * 获取小b账号密码
     *
     * @param request
     * @return
     */
    @GetMapping("/getbaccount")
    public Map<String, String> getBAccount(HttpServletRequest request) throws IOException, URISyntaxException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        return mallBoomService.getSalerAccount(customerId);
    }


    /**
     * 联盟商城列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getallmallboomgoods")
    public Object getAllMallBoomGoods(@RequestParam(value = "source", defaultValue = "step", required = false) String source,
                                      @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                      @RequestParam(value = "order", defaultValue = "time", required = false) String order,
                                      @RequestParam(value = "sort", defaultValue = "desc", required = false) String sort,
                                      @RequestParam(value = "type", defaultValue = "", required = false) String type,
                                      @RequestParam(value = "goodsType", defaultValue = "0", required = false) Integer goodsType,
                                      @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword,
                                      @RequestParam(value = "catId", defaultValue = "0", required = false) Integer catId,
                                      @RequestParam(value = "catPid", defaultValue = "0", required = false) Integer catPid,
                                      @RequestParam(value = "salerId", defaultValue = "", required = false) String salerId,
                                      HttpServletRequest request) throws IOException, URISyntaxException, GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        String customerId = wxUser.getCustomerId();
        String forder = "upTime";
        if ("money".equals(order)) {
            forder = "moneyAmount";
        }
        String fsort = "DESC";
        if ("a".equals(sort)) {
            fsort = "ASC";
        }
        Map<String, Object> sqlparam = new HashMap<>();
        sqlparam.put("orgId", orgId);
        sqlparam.put("order", forder);
        sqlparam.put("sort", fsort);
        sqlparam.put("customerId", customerId);
        sqlparam.put("type", type);
        sqlparam.put("goodsType", goodsType);
        sqlparam.put("salerId", salerId);

        if (pageIndex < 1) {
            pageIndex = 1;
        }
        sqlparam.put("pageIndex", (pageIndex - 1) * pageSize);
        sqlparam.put("pageSize", pageSize);
        if ("dong".equals(source)) {
            sqlparam.put("dongStatus", 1);
            sqlparam.put("keyword", keyword);
            if(catId!=0){
                sqlparam.put("catId", catId);
            }else if(catPid!=0){
                sqlparam.put("catPid", catPid);
            }
        }
        Integer daCount = mallBoomService.getGoodsCount(sqlparam);
        List<Map<String, Object>> allMallBoomGoodsList = mallBoomService.getAllMallBoomGoods(sqlparam);
        for (Map<String, Object> map : allMallBoomGoodsList) {
            Long goodsType1 = Long.valueOf(map.get("goodsType").toString());
            if (goodsType1 != null && goodsType1 == 9) {
                String goodsId = map.get("goodsId").toString();
                int enrollStatus = enrollActiveService.getEnrollStatus(goodsId);
                map.put("status", enrollStatus);
            } else {
                map.put("status", null);
            }
        }
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_LIST_BY_IDS;
        List<Map<String, Object>> resList = new ArrayList<>();
        List<Map<String, Object>> daList = new ArrayList<>();
        StringBuilder articleIds = new StringBuilder();
        Map<String, Integer> reverseProfitModel = mallBoomDao.getReverseProfitModel(orgId);// 返润模式
        Integer serviceRatio;// 商品服务费占比例,eg:50
        Integer recommendRatio;// 商品推荐费占比例,eg:50
        if (reverseProfitModel == null) {
            // 机构没有设置返润模式
            serviceRatio = 50;
            recommendRatio = 50;
        } else {
            serviceRatio = reverseProfitModel.get("serviceRatio");
            recommendRatio = reverseProfitModel.get("recommendRatio");
        }
        for (Map<String, Object> val : allMallBoomGoodsList) {
            // todo 最小-最大
            Long moneyAmount = (Long) val.get("moneyAmount");
            Long maxMoneyAmount = (Long) val.get("maxMoneyAmount");
            String rebateStr = (String) val.get("rebate");
            Double rebate = Double.valueOf(rebateStr);
            double v1 = rebate * serviceRatio.doubleValue() * moneyAmount.doubleValue() / 1000000;
            double v2 = rebate * recommendRatio.doubleValue() * moneyAmount.doubleValue() / 1000000;
            double v3 = rebate * maxMoneyAmount.doubleValue() / 10000;
            String s1 = new BigDecimal(v1).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            String s2 = new BigDecimal(v2).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            String s3 = new BigDecimal(v3).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
            if (v1 < v2) {
                val.put("min", s1);
                val.put("max", s3);
            } else {
                val.put("min", s2);
                val.put("max", s3);
            }
            if (!"".equals(val.get("articleId"))) {
                articleIds.append(",").append(val.get("articleId"));
            }
//            Long skuMoney = mallBoomService.getSkuMoneyByGoodsId(val.get("goodsId").toString());
            Long skuMoney = (Long) val.get("moneyAmount");
            if (null != skuMoney && skuMoney > 0) {
                val.put("moneyAmount", NumberUtils.fenToYuan(skuMoney));
            } else {
                val.put("moneyAmount", val.get("moneyAmount") == null ? "0" : NumberUtils.fenToYuan(Long.valueOf(val.get("moneyAmount").toString())));
            }
        }
        Map<String, Object> resData = new HashMap<String, Object>();
        resData.put("ids", articleIds.toString());
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(resData);
        String postres;
        if (goodsType == 0 || goodsType == 3) {
            // 商品类型 0 全部 1 商品 2 知识付费 3 文章 4 报名
            postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        } else {
            postres = null;
        }
        if (null != postres) {
            Map res = (Map) JSON.parse(postres);
            if ("200".equals(res.get("code").toString())) {
                resList = (ArrayList) res.get("data");
                for (Map<String, Object> da : allMallBoomGoodsList) {
                    Map<String, Object> tmp = new HashMap<String, Object>();
                    tmp.put("goods", da);
                    Object arttmp = new HashMap<>();
                    for (Map<String, Object> va : resList) {
                        if (da.get("articleId").equals(va.get("id").toString())) {
                            arttmp = va;
                        }
                    }
                    tmp.put("news", arttmp);
                    daList.add(tmp);
                }
            } else {
                for (Map<String, Object> da : allMallBoomGoodsList) {
                    Map<String, Object> tmp = new HashMap<String, Object>();
                    tmp.put("goods", da);
                    Object arttmp = new HashMap<>();
                    tmp.put("news", arttmp);
                    daList.add(tmp);
                }
            }
        } else {
            for (Map<String, Object> da : allMallBoomGoodsList) {
                Map<String, Object> tmp = new HashMap<String, Object>();
                tmp.put("goods", da);
                Object arttmp = new HashMap<>();
                tmp.put("news", arttmp);
                daList.add(tmp);
            }
        }
        Map<String, Object> finalData = new HashMap<>();
        finalData.put("count", daCount);
        finalData.put("pageIndex", pageIndex);
        finalData.put("list", daList);
        return finalData;
    }


    /**
     * 获取文章详情
     *
     * @param articleId
     * @return
     */
    @GetMapping("/getarticledetail")
    public Map getArticleDetail(String articleId) throws GlobalException, IOException, URISyntaxException {
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_DETAIL;
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> resData = new HashMap<String, Object>();
        param.put("newsId", articleId);
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
        String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        LOGGER.info("getarticledetail===result===" + postres);
        if (null != postres) {
            Map res = (Map) JSON.parse(postres);
            if ("200".equals(res.get("code").toString())) {
                if (res.get("data") == null) {
                    throw GlobalException.build("暂无文章数据");
                }
                resData.put("newsName", ((Map) res.get("data")).get("newsName"));
                resData.put("createTime", ((Map) res.get("data")).get("createTime"));
                resData.put("newsSummary", ((Map) res.get("data")).get("newsSummary"));
                resData.put("newsContent", ((Map) res.get("data")).get("newsContent"));
                resData.put("headPicUrl", ((Map) res.get("data")).get("headPicUrl"));
                resData.put("newsCover", ((Map) res.get("data")).get("newsCover"));
                resData.put("shortUrl", ((Map) res.get("data")).get("shortUrl"));
                resData.put("url", ((Map) res.get("data")).get("url"));
                resData.put("newsAuthor", ((Map) res.get("data")).get("newsAuthor"));
            } else {
                throw GlobalException.build("请求失败");
            }
        } else {
            throw GlobalException.build("请求失败");
        }
        return resData;
    }


    /**
     * 设置推广页面过期时间
     *
     * @param params
     * @return
     * @throws GlobalException
     */
    @PostMapping("/setqrcodecache")
    public Boolean setQrcodeChche(@RequestBody Map<String, String> params) throws GlobalException {
        String cacheId = params.get("cacheId");
        if (null == cacheId || "".equals(cacheId)) {
            throw GlobalException.build("key为空，设置失败");
        }
        stringRedisTemplate.opsForValue().set(cacheId, "1", 300, TimeUnit.SECONDS);
        return true;
    }


    /**
     * 获取推广页面过期时间
     *
     * @param cacheId
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getqrcodecache")
    public Boolean getQrcodeChche(@RequestParam(value = "cacheId", defaultValue = "", required = false) String cacheId) throws GlobalException {
        if ("".equals(cacheId)) {
            throw GlobalException.build("key为空，获取失败");
        }
        String str = stringRedisTemplate.opsForValue().get(cacheId);
        return null != str;
    }

    @PostMapping("/delivery")
    public int delivery(@RequestBody Map<String, Object> record, HttpServletRequest request) throws UnsupportedEncodingException {
        WxUser wxUser =  requestFilter.getWxUser(request);


        Long expressId = null;
        if (record.get("expressId").toString() != null && !record.get("expressId").toString().equals("")) {
            expressId = Long.valueOf(record.get("expressId").toString());
        }
        String expressName = null;
        if (record.get("expressName").toString() != null && !record.get("expressName").toString().equals("")) {
            expressName = record.get("expressName").toString();
        }
        Long orderId = Long.valueOf(record.get("orderId").toString());
        String goodsIds = record.get("goodsIds").toString();
        String shippingCode = record.get("shippingCode").toString();
        Integer shippingType = Integer.parseInt(record.get("shippingType").toString());

        net.sf.json.JSONArray jsonarr = net.sf.json.JSONArray.fromObject(goodsIds);
        List<OrderGoods> orderList = new ArrayList<>();
        if (jsonarr.size() > 0) {
            for (int i = 0; i < jsonarr.size(); i++) {
                OrderGoods order = new OrderGoods();
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                net.sf.json.JSONObject job = jsonarr.getJSONObject(i);
                order.setGoodsId(Long.valueOf(job.get("goodsId").toString()));
                order.setRecId(Long.valueOf(job.get("recId").toString()));
                if (job.get("newsku") == null) {
                    order.setSkuInfo(null);
                } else {
                    order.setSkuInfo(job.get("newsku").toString());
                }
                orderList.add(order);
            }
        }
        String orgId = wxUser.getOrgId();
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("orderId", orderId);
        params.put("expressId", expressId);
        params.put("expressName", expressName);
        params.put("goodsIds", orderList);
        params.put("shippingCode", shippingCode);
        params.put("shippingType", shippingType);
        Integer payMode = mallBoomDao.getPayModeByOrgId(params);
        if (payMode == null) {
            payMode = 0;
        }
        params.put("payMode", payMode);
        //剩余未发货个数
        int count = mallBoomService.delivery(params);
        //获取手机号和公众号名称
        Map<String, Object> msgInfo = mallBoomService.getMsgInfo(params);
        String phone = (String) msgInfo.get("phone");
        String publicName = (String) msgInfo.get("publicName");
        //TODO 发货通知

        //发货通知(模板)
        Map orderInfo = mallBoomService.getOrderInfoById(orderId, payMode);
        String receiveInfo = orderInfo.get("realName") + " " + orderInfo.get("phone") + " " + orderInfo.get("province") + orderInfo.get("city") + orderInfo.get("area") + orderInfo.get("address");
        Map<String, String> orderParam = new HashMap<>();
        orderParam.put("sendType", "delivery");
        orderParam.put("orgId", orderInfo.get("orgId").toString());
        orderParam.put("orderSn", (String) orderInfo.get("orderSn"));
        String sendTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orderParam.put("sendTime", sendTime);
        orderParam.put("expressCompany", expressName == null ? "不需要物流" : expressName);
        orderParam.put("expressSn", shippingType == 0 ? "不需要物流" : shippingCode);
        orderParam.put("receiveInfo", receiveInfo);

        String h5url = scrmH5Url + "/userCenter.html?goto=orderlist?activeTab=30";
        String h5urlEncode = URLEncoder.encode(h5url, "UTF-8");
        String url = clientHost + "/personal/login?token=" + purchaseProcessDao.getTokenByOrgId(orderInfo.get("orgId").toString()) + "&m=" + h5urlEncode;

        orderParam.put("url", url);
        orderParam.put("openid", purchaseProcessDao.getOpenIdByCustomerId((String) orderInfo.get("customerId")));
        purchaseProcessService.setTemplateMessageList(orderParam);

//        List<NameValuePair> nvps = new ArrayList<>();
//        nvps.add(new BasicNameValuePair("businessType", "9001"));
//        nvps.add(new BasicNameValuePair("plantName", "STEPLINK"));
//        nvps.add(new BasicNameValuePair("mobilNumber", phone));
//        nvps.add(new BasicNameValuePair("params", "{name=" + publicName + "公众号}"));
//        nvps.add(new BasicNameValuePair("token", null));
//        String result = ParamSignUtils.callService(smsurl + "/sms/sendMessage", nvps, 0, 0);

        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", "9001");
        nvps.put("mobilNumber", phone);
        nvps.put("params", "{name=" + publicName + "公众号}");
        nvps.put("token", null);
        String result = smsService.sendMsg(orgId, nvps);

        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            //todo 记录短信发送失败日志
        }
        return count;
    }
}
